//
//  NSAttributeString+Extension.swift
//  weibo
//
//  Created by 阿城 on 15/12/18.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit

extension NSAttributedString{
    
     class func multiStringWithString(originalStr: String, regularStr: String, backClosure: (range:NSRange, subStr:String)->()){

        do{
            let regular =  try NSRegularExpression(pattern: regularStr, options: NSRegularExpressionOptions.CaseInsensitive)
            let checkResult = regular.firstMatchInString(originalStr, options: NSMatchingOptions.ReportCompletion, range: NSRange(location: 0, length: originalStr.characters.count))
            if let result = checkResult{
                let subStr = (originalStr as NSString).substringWithRange(result.range)
                backClosure(range: result.range, subStr: subStr)
            }else{
                return
            }
            
        }catch {
            print(error)
        }
    }
    
    
    class func emoticonWithString(originalStr: NSAttributedString, regularStr: String) -> NSAttributedString{
    
        return exchangeWithString(originalStr, regularStr: regularStr, backClosure: { (attr, range) -> () in
            
            let subStr = (attr.string as NSString).substringWithRange(range)
            var append = NSAttributedString()
            if let emoticon = SCEmoticonViewModel.shareEmoticons.findEmoticon(subStr){
                append = SCAttachment().getEmoticonAttributedString(emoticon, font: UIFont.systemFontOfSize(kStatusFont))
            }
            attr.replaceCharactersInRange(range, withAttributedString: append)
        })
    }
    
    class func highLightedWithString(originalStr: NSAttributedString, regularStr: String) -> NSAttributedString{
       
        return exchangeWithString(originalStr, regularStr: regularStr, backClosure: { (attr, range) -> () in
            attr.addAttribute(NSForegroundColorAttributeName, value:SCColor.getColor(80, G: 125, B: 175) , range: range)
        })
    }
    
    private class func exchangeWithString(originalStr: NSAttributedString, regularStr: String, backClosure:(attr: NSMutableAttributedString, range: NSRange)->()) -> NSAttributedString{
        
        let attr = NSMutableAttributedString(attributedString: originalStr)
        
        do{
            let regular =  try NSRegularExpression(pattern: regularStr, options: NSRegularExpressionOptions.CaseInsensitive)
            let checkResult = regular.firstMatchInString(attr.string, options: NSMatchingOptions.ReportCompletion, range: NSRange(location: 0, length: attr.length))
            
            if let result = checkResult{
                
                backClosure(attr: attr, range: result.range)
                
            }else{
                return attr
            }
            
        }catch {
            print(error)
        }
        return emoticonWithString(attr, regularStr: regularStr)
    }
    
}